package web.servlet;

import jdbc.domain.Account;
import service.AccountService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


public class SignOnServlet extends HttpServlet {
    private String username;
    private String password;

    private String signOnMsg;

    private static final String FORM="/index.jsp";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.username = req.getParameter("username");
        this.password = req.getParameter("password");

        if(!validate()){
            req.setAttribute("signOnMsg", signOnMsg);
            req.getRequestDispatcher(FORM).forward(req, resp);
        }
        else {
            AccountService accountService = new AccountService();
            Account loginAccount=accountService.getUser(username, password);
            if(loginAccount==null){
                signOnMsg="Invalid username or password";
                req.setAttribute("signOnMsg", signOnMsg);
                req.getRequestDispatcher(FORM).forward(req, resp);
            }
            else {
                loginAccount.setPassword(null);
                HttpSession session=req.getSession();
                session.setAttribute("loginAccount", loginAccount);

//                if(loginAccount.isListOption()){
//                    CatalogService catalogService=new  CatalogService();
//                    List<Product> myList=catalogService.getProductListByCategory(loginAccount.getFavouriteCategoryId());
//                    session.setAttribute("myList", myList);
//                }

                resp.sendRedirect("mainForm");
            }
        }
    }

    private boolean validate(){
        if(this.username !=null ){
            this.signOnMsg = "Username is required";
            return false;
        }
        if(this.password !=null){
            this.signOnMsg = "Password is required";
            return false;
        }
        return true;
    }
}
